/**
 * Phase 2 控制器 - 多进程架构API
 * EndoSight-UC 医疗AI系统
 *
 * 提供多进程管理器的REST API接口
 * 暴露工作器状态、队列监控和增强推理功能
 */

import processManager from '../config/processManager.js';
import enhancedAIInferenceService from '../services/enhancedAIInferenceService.js';
import { InferencePriority } from '../services/enhancedAIInferenceService.js';
import auditService from '../services/auditService.js';

/**
 * 获取进程管理器系统状态
 */
export const getProcessStatus = async (req, res) => {
  try {
    const systemStatus = processManager.getSystemStatus();

    // 记录访问日志
    await auditService.logMedicalDataAccess({
      userId: req.user?.id || 'anonymous',
      sessionId: req.sessionId,
      patientId: null,
      dataType: 'system_status',
      accessType: 'view',
      accessReason: 'Phase 2进程管理器状态查询',
      dataBefore: null,
      dataAfter: {
        endpoint: '/api/process/status',
        timestamp: new Date().toISOString()
      }
    });

    res.json({
      success: true,
      message: 'Phase 2 进程管理器状态获取成功',
      data: {
        processManager: {
          isRunning: systemStatus.isRunning,
          startTime: systemStatus.startTime,
          uptime: systemStatus.uptime,
          correlationId: systemStatus.correlationId,
          totalWorkers: systemStatus.totalWorkers,
          totalTasksProcessed: systemStatus.totalTasksProcessed,
          totalErrors: systemStatus.totalErrors
        },
        workers: systemStatus.workersByType,
        systemInfo: systemStatus.systemInfo,
        timestamp: new Date().toISOString()
      }
    });

  } catch (error) {
    console.error('获取进程状态失败:', error);
    res.status(500).json({
      success: false,
      message: '获取进程状态失败',
      error: error.message
    });
  }
};

/**
 * 获取工作器详细状态
 */
export const getWorkersStatus = async (req, res) => {
  try {
    const systemStatus = processManager.getSystemStatus();
    const workersByType = systemStatus.workersByType;

    // 记录访问日志
    await auditService.logMedicalDataAccess({
      userId: req.user?.id || 'anonymous',
      sessionId: req.sessionId,
      patientId: null,
      dataType: 'worker_status',
      accessType: 'view',
      accessReason: 'Phase 2工作器状态查询',
      dataBefore: null,
      dataAfter: {
        endpoint: '/api/workers/status',
        workerTypes: Object.keys(workersByType)
      }
    });

    // 统计工作器状态
    const workerStats = {
      total: 0,
      healthy: 0,
      idle: 0,
      busy: 0,
      error: 0,
      overloaded: 0,
      terminated: 0,
      averageHealthScore: 0,
      averageMemoryUsage: 0,
      types: {}
    };

    let totalHealthScore = 0;
    let totalMemoryUsage = 0;
    let workerCount = 0;

    for (const [type, workers] of Object.entries(workersByType)) {
      const typeStats = {
        count: workers.length,
        healthy: 0,
        idle: 0,
        busy: 0,
        error: 0,
        overloaded: 0,
        terminated: 0,
        averageHealthScore: 0,
        averageMemoryUsage: 0
      };

      let typeHealthScore = 0;
      let typeMemoryUsage = 0;

      for (const worker of workers) {
        workerStats.total++;

        switch (worker.status) {
          case 'idle':
            workerStats.idle++;
            typeStats.idle++;
            break;
          case 'busy':
            workerStats.busy++;
            typeStats.busy++;
            break;
          case 'error':
            workerStats.error++;
            typeStats.error++;
            break;
          case 'overloaded':
            workerStats.overloaded++;
            typeStats.overloaded++;
            break;
          case 'terminated':
            workerStats.terminated++;
            typeStats.terminated++;
            break;
          default:
            // 默认认为健康
            workerStats.healthy++;
            typeStats.healthy++;
            break;
        }

        typeHealthScore += worker.healthScore || 0;
        typeMemoryUsage += worker.memoryUsage || 0;
      }

      if (workers.length > 0) {
        typeStats.averageHealthScore = Math.round(typeHealthScore / workers.length);
        typeStats.averageMemoryUsage = Math.round(typeMemoryUsage / workers.length);
      }

      totalHealthScore += typeHealthScore;
      totalMemoryUsage += typeMemoryUsage;
      workerCount += workers.length;
      workerStats.types[type] = typeStats;
    }

    if (workerCount > 0) {
      workerStats.averageHealthScore = Math.round(totalHealthScore / workerCount);
      workerStats.averageMemoryUsage = Math.round(totalMemoryUsage / workerCount);
      workerStats.healthy = workerStats.total - workerStats.busy - workerStats.error - workerStats.overloaded - workerStats.terminated;
    }

    res.json({
      success: true,
      message: '工作器状态获取成功',
      data: {
        summary: workerStats,
        details: workersByType,
        timestamp: new Date().toISOString()
      }
    });

  } catch (error) {
    console.error('获取工作器状态失败:', error);
    res.status(500).json({
      success: false,
      message: '获取工作器状态失败',
      error: error.message
    });
  }
};

/**
 * 获取队列监控信息
 */
export const getQueueMonitor = async (req, res) => {
  try {
    // 获取增强AI推理服务状态
    const inferenceServiceStatus = enhancedAIInferenceService.getServiceStatus();

    // 获取进程管理器状态
    const systemStatus = processManager.getSystemStatus();

    // 记录访问日志
    await auditService.logMedicalDataAccess({
      userId: req.user?.id || 'anonymous',
      sessionId: req.sessionId,
      patientId: null,
      dataType: 'queue_monitor',
      accessType: 'view',
      accessReason: 'Phase 2队列监控查询',
      dataBefore: null,
      dataAfter: {
        endpoint: '/api/queues/monitor'
      }
    });

    // 整合队列信息
    const queueData = {
      enhancedInferenceService: {
        isRunning: inferenceServiceStatus.isRunning,
        metrics: inferenceServiceStatus.metrics,
        tasksByStatus: inferenceServiceStatus.tasksByStatus,
        queueByPriority: inferenceServiceStatus.queueByPriority,
        processingTasks: inferenceServiceStatus.processingTasks,
        completedTasksCache: inferenceServiceStatus.completedTasksCache,
        correlationId: inferenceServiceStatus.correlationId
      },
      processManager: {
        isRunning: systemStatus.isRunning,
        totalWorkers: systemStatus.totalWorkers,
        totalTasksProcessed: systemStatus.totalTasksProcessed,
        workersByType: systemStatus.workersByType
      },
      systemMetrics: {
        totalWorkersActive: inferenceServiceStatus.metrics.workersActive,
        queueLength: inferenceServiceStatus.metrics.queueLength,
        totalTasksProcessed: inferenceServiceStatus.metrics.totalTasksProcessed,
        completedTasks: inferenceServiceStatus.metrics.completedTasks,
        failedTasks: inferenceServiceStatus.metrics.failedTasks,
        averageProcessingTime: inferenceServiceStatus.metrics.averageProcessingTime
      }
    };

    res.json({
      success: true,
      message: '队列监控信息获取成功',
      data: {
        queues: queueData,
        performance: {
          processingRate: inferenceServiceStatus.metrics.completedTasks > 0
            ? (inferenceServiceStatus.metrics.completedTasks / (Date.now() - inferenceServiceStatus.startTime)) * 1000
            : 0,
          errorRate: inferenceServiceStatus.metrics.totalTasksProcessed > 0
            ? (inferenceServiceStatus.metrics.failedTasks / inferenceServiceStatus.metrics.totalTasksProcessed) * 100
            : 0,
          averageProcessingTime: inferenceServiceStatus.metrics.averageProcessingTime
        },
        timestamp: new Date().toISOString()
      }
    });

  } catch (error) {
    console.error('获取队列监控信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取队列监控信息失败',
      error: error.message
    });
  }
};

/**
 * 提交增强AI推理任务
 */
export const submitEnhancedInference = async (req, res) => {
  try {
    const { patientId, images, priority = InferencePriority.NORMAL, metadata = {} } = req.body;

    // 验证必需字段
    if (!patientId || !images || !Array.isArray(images) || images.length === 0) {
      return res.status(400).json({
        success: false,
        message: '缺少必需字段：patientId、images'
      });
    }

    // 验证用户权限
    if (!req.user) {
      return res.status(401).json({
        success: false,
        message: '需要认证'
      });
    }

    // 验证图像数据
    for (const image of images) {
      if (!image.id || !image.path) {
        return res.status(400).json({
          success: false,
          message: '图像数据不完整，缺少id或path字段'
        });
      }
    }

    const taskData = {
      patientId,
      doctorId: req.user.id,
      sessionId: req.sessionId,
      images,
      priority,
      metadata: {
        ...metadata,
        submittedAt: new Date().toISOString(),
        userAgent: req.get('User-Agent'),
        ip: req.ip
      }
    };

    // 提交任务到增强AI推理服务
    const result = await enhancedAIInferenceService.submitInferenceTask(taskData);

    // 记录任务提交日志
    await auditService.logMedicalDataAccess({
      userId: req.user.id,
      sessionId: req.sessionId,
      patientId,
      dataType: 'ai_inference',
      accessType: 'create',
      accessReason: 'Phase 2增强AI推理任务提交',
      dataBefore: null,
      dataAfter: {
        taskId: result.taskId,
        imageCount: images.length,
        priority
      }
    });

    res.status(201).json({
      success: true,
      message: '增强AI推理任务提交成功',
      data: {
        taskId: result.taskId,
        status: result.status,
        queuePosition: result.queuePosition,
        estimatedWaitTime: result.estimatedWaitTime,
        submittedAt: new Date().toISOString()
      }
    });

  } catch (error) {
    console.error('提交增强AI推理任务失败:', error);
    res.status(500).json({
      success: false,
      message: '提交增强AI推理任务失败',
      error: error.message
    });
  }
};

/**
 * 获取推理任务状态
 */
export const getInferenceTaskStatus = async (req, res) => {
  try {
    const { taskId } = req.params;

    if (!taskId) {
      return res.status(400).json({
        success: false,
        message: '缺少任务ID'
      });
    }

    const taskStatus = enhancedAIInferenceService.getTaskStatus(taskId);

    // 记录访问日志
    await auditService.logMedicalDataAccess({
      userId: req.user?.id || 'anonymous',
      sessionId: req.sessionId,
      patientId: taskStatus.data?.patientId || null,
      dataType: 'inference_status',
      accessType: 'view',
      accessReason: 'Phase 2推理任务状态查询',
      dataBefore: null,
      dataAfter: {
        taskId,
        status: taskStatus.status
      }
    });

    if (!taskStatus.found) {
      return res.status(404).json({
        success: false,
        message: '任务不存在'
      });
    }

    res.json({
      success: true,
      message: '任务状态获取成功',
      data: taskStatus
    });

  } catch (error) {
    console.error('获取推理任务状态失败:', error);
    res.status(500).json({
      success: false,
      message: '获取推理任务状态失败',
      error: error.message
    });
  }
};

/**
 * 取消推理任务
 */
export const cancelInferenceTask = async (req, res) => {
  try {
    const { taskId } = req.params;
    const { reason } = req.body;

    if (!taskId) {
      return res.status(400).json({
        success: false,
        message: '缺少任务ID'
      });
    }

    // 验证用户权限
    if (!req.user) {
      return res.status(401).json({
        success: false,
        message: '需要认证'
      });
    }

    await enhancedAIInferenceService.cancelTask(taskId, reason || '用户取消');

    // 记录取消日志
    await auditService.logMedicalDataAccess({
      userId: req.user.id,
      sessionId: req.sessionId,
      patientId: null,
      dataType: 'inference_cancel',
      accessType: 'delete',
      accessReason: `Phase 2推理任务取消: ${reason}`,
      dataBefore: {
        taskId
      },
      dataAfter: {
        taskId,
        reason
      }
    });

    res.json({
      success: true,
      message: '推理任务取消成功',
      data: {
        taskId,
        cancelledAt: new Date().toISOString()
      }
    });

  } catch (error) {
    console.error('取消推理任务失败:', error);
    res.status(500).json({
      success: false,
      message: '取消推理任务失败',
      error: error.message
    });
  }
};

/**
 * 获取系统性能指标
 */
export const getPerformanceMetrics = async (req, res) => {
  try {
    const systemStatus = processManager.getSystemStatus();
    const inferenceStatus = enhancedAIInferenceService.getServiceStatus();

    // 记录访问日志
    await auditService.logMedicalDataAccess({
      userId: req.user?.id || 'anonymous',
      sessionId: req.sessionId,
      patientId: null,
      dataType: 'performance_metrics',
      accessType: 'view',
      accessReason: 'Phase 2系统性能指标查询',
      dataBefore: null,
      dataAfter: null
    });

    const metrics = {
      system: {
        uptime: systemStatus.uptime,
        totalWorkers: systemStatus.totalWorkers,
        totalTasksProcessed: systemStatus.totalTasksProcessed,
        totalErrors: systemStatus.totalErrors,
        correlationId: systemStatus.correlationId,
        systemInfo: systemStatus.systemInfo
      },
      inference: {
        isRunning: inferenceStatus.isRunning,
        metrics: inferenceStatus.metrics,
        tasksByStatus: inferenceStatus.tasksByStatus,
        processingTasks: inferenceStatus.processingTasks,
        queueLength: inferenceStatus.metrics.queueLength,
        averageProcessingTime: inferenceStatus.metrics.averageProcessingTime
      },
      workers: systemStatus.workersByType,
      performance: {
        tasksPerSecond: inferenceStatus.metrics.completedTasks > 0
          ? inferenceStatus.metrics.completedTasks / (inferenceStatus.metrics.queueLength || 1)
          : 0,
        errorRate: inferenceStatus.metrics.totalTasksProcessed > 0
          ? (inferenceStatus.metrics.failedTasks / inferenceStatus.metrics.totalTasksProcessed) * 100
          : 0,
        throughput: inferenceStatus.metrics.completedTasks
      }
    };

    res.json({
      success: true,
      message: '系统性能指标获取成功',
      data: metrics,
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    console.error('获取性能指标失败:', error);
    res.status(500).json({
      success: false,
      message: '获取性能指标失败',
      error: error.message
    });
  }
};

/**
 * 重启特定类型的工作器
 */
export const restartWorkers = async (req, res) => {
  try {
    const { workerType, force = false } = req.body;

    // 验证权限 - 只有管理员才能重启工作器
    if (!req.user || req.user.role !== 'admin') {
      return res.status(403).json({
        success: false,
        message: '需要管理员权限'
      });
    }

    // 记录操作日志
    await auditService.logSystemConfigChange({
      userId: req.user.id,
      sessionId: req.sessionId,
      configCategory: 'system',
      configKey: 'worker_restart',
      oldValue: null,
      newValue: { workerType, force, timestamp: new Date().toISOString() },
      changeReason: req.body.reason || '管理员手动重启工作器',
      approvalRequired: true,
      approvedBy: req.user.id,
      approvalTimestamp: new Date().toISOString()
    });

    // TODO: 实现工作器重启逻辑
    // 这里需要调用进程管理器的重启功能

    res.json({
      success: true,
      message: '工作器重启指令已发送',
      data: {
        workerType,
        force,
        timestamp: new Date().toISOString()
      }
    });

  } catch (error) {
    console.error('重启工作器失败:', error);
    res.status(500).json({
      success: false,
      message: '重启工作器失败',
      error: error.message
    });
  }
};